Today, you will load a filtered gapminder dataset - with a subset of data on global development from 1952 - 2007 in increments of 5 years - to capture the period between the Second World War and the Global Financial Crisis.
Your task: Explore the data and visualise it in both static and animated ways, providing answers and solutions to 7 questions/tasks below.
First, start with installing the relevant packages ‘tidyverse’, ‘gganimate’, and ‘gapminder’.
## -- Attaching packages -------------------------------------------------------------------------------------------------------- tidyverse 1.3.0 --
## v ggplot2 3.3.2 v purrr 0.3.4
## v tibble 3.0.3 v dplyr 1.0.2
## v tidyr 1.1.2 v stringr 1.4.0
## v readr 1.3.1 v forcats 0.5.0
## -- Conflicts ----------------------------------------------------------------------------------------------------------- tidyverse_conflicts() --
## x dplyr::filter() masks stats::filter()
## x dplyr::lag() masks stats::lag()
First, see which specific years are actually represented in the dataset and what variables are being recorded for each country. Note that when you run the cell below, Rmarkdown will give you two results - one for each line - that you can flip between.
unique(gapminder$year) #Here I look at the unique times years is displayed in the gapminder dataset
## [1] 1952 1957 1962 1967 1972 1977 1982 1987 1992 1997 2002 2007
head(gapminder) #Looking at the start of the gapminder dataset
## # A tibble: 6 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
tail(gapminder) #Looking at the end of the gapminder dataset
## # A tibble: 6 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Zimbabwe Africa 1982 60.4 7636524 789.
## 2 Zimbabwe Africa 1987 62.4 9216418 706.
## 3 Zimbabwe Africa 1992 60.4 10704340 693.
## 4 Zimbabwe Africa 1997 46.8 11404948 792.
## 5 Zimbabwe Africa 2002 40.0 11926563 672.
## 6 Zimbabwe Africa 2007 43.5 12311143 470.
The dataset contains information on each country in the sampled year, its continent, life expectancy, population, and GDP per capital.
Let’s plot all the countries in 1952.
theme_set(theme_bw()) # set theme to white background for better visibility
ggplot(subset(gapminder, year == 1952), aes(gdpPercap, lifeExp, size = pop)) + #I use the ggplot to make visualizations. I am using "subset to look at the year year 1952 in the gapminder data set
# aes is used to make the astetics. we set gdpPercap as the x-axis, lifeExp the y-axis and pop as the size
geom_point() + #geom_point() gør at vi får scatter plots altså prikker i vores kordinatsystem
scale_x_log10() #convert x to log scale
We see an interesting spread with an outlier to the right. Answer the following questions, please:
Q1. Why does it make sense to have a log10 scale on x axis?
If we do not ad the “log10()” line the we will still get a graph, but since there is one value that lies a long way away from the others, we will get a very long graph, which is not easy to read. Instead if we scale the x-axis we make the graph smaller, and also easier to comprehend as the different values are more distinguishable from each other.
Q2. What country is the richest in 1952 (far right on x axis)?
To find out which country is the richest in 1952, we must use the “gdpPercap” column to read which is the largest har the largest number and is there by the richest country.
gapminder %>% #We choose to look at the gapminder dataset and add pipes to it, so we can send an output of one fucntion directly to another.
filter(year == 1952) %>% #First we filter the years in tha dataset so vi are only looking at data from 1952
select(country , gdpPercap) %>% #then we select or choose to look at the countries and their gdpPercap, as everything else is irelevant right now
arrange(desc(gdpPercap)) #lastly, we arange our data in a decending order so we have the richest nation first.
## # A tibble: 142 x 2
## country gdpPercap
## <fct> <dbl>
## 1 Kuwait 108382.
## 2 Switzerland 14734.
## 3 United States 13990.
## 4 Canada 11367.
## 5 New Zealand 10557.
## 6 Norway 10095.
## 7 Australia 10040.
## 8 United Kingdom 9980.
## 9 Bahrain 9867.
## 10 Denmark 9692.
## # ... with 132 more rows
From the above we can read that the richest country by far in 1552 was Kuwait.
You can generate a similar plot for 2007 and compare the differences
ggplot(subset(gapminder, year == 2007), aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10()
The black bubbles are a bit hard to read, the comparison would be easier with a bit more visual differentiation.
Q3. Can you differentiate the continents by color and fix the axis labels?
ggplot(subset(gapminder, year == 2007), aes(x = gdpPercap, y = lifeExp, size = pop, color = continent)) + #here i use the same line of code as above and ad "color = continent" to color the different continents.
#further more we add x and y, so it is easier to change lator in the code.
geom_point(alpha = 0.5) + # alpha gives us the opportunity to make the points more transparent on a scale from 0 -1
labs(title = "Coutries in 2007", x = "GDP Per Capita", y = "Life Expectancy") + #Here we use labs to give the visualization a title and rename the x and y axis.
scale_x_log10() + # convert x to log scale
scale_size(range = c(1, 15), name="Population") #Here we scale up the size of the points in the visualization so they are easier to see. Further more we are renaming pop to Population
Q4. What are the five richest countries in the world in 2007?
gapminder %>% # We look at gapminder and use the pipes (%>%) as arguments for the next lines
filter(year == 2007) %>% #We filter on the year 2007
select(country , gdpPercap) %>% #and chose to look at country and gdpPercap
arrange(desc(gdpPercap)) %>% #aranging the data in decending order
head(5) #and looking at the first 5.
## # A tibble: 5 x 2
## country gdpPercap
## <fct> <dbl>
## 1 Norway 49357.
## 2 Kuwait 47307.
## 3 Singapore 47143.
## 4 United States 42952.
## 5 Ireland 40676.
By using the almost the same code as in Question 2 and adding head 5 we can show the 5 richest countries in 2007 by reading from the chart we can see that the richest contries are Norway, Kuwait, Singapore, Unitid States and Ireland.
The comparison would be easier if we had the two graphs together, animated. We have a lovely tool in R to do this: the gganimate package. And there are two ways of animating the gapminder ggplot.
The first step is to create the object-to-be-animated
anim <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) + #Here we make an object named anim, where we use the illustration tool ggplot and use it on the gapminder dataset. The aestetics of the illustration is afterwards determined with gdppercap as the x-axis. lifeExp as the y-axis and population as size of the points.
geom_point() + #here we choose the style of the plot to be geom.
scale_x_log10() # convert x to log scale
anim #call the object.
This plot collates all the points across time. The next step is to split it into years and animate it. This may take some time, depending on the processing power of your computer (and other things you are asking it to do). Beware that the animation might appear in the ‘Viewer’ pane, not in this rmd preview. You need to knit the document to get the viz inside an html file.
anim + transition_states(year,
transition_length = 1,
state_length = 1)#+
# labs(title = "{closest_state}") +
# transition_states(year, transition_length = 12, state_length = 1, wrap = TRUE)
#The last two lines, have I added and commented out, but they fix the problem, makes the illustration, more fluid and puts changing headlines above the illustration - more explanation futher down.
Notice how the animation moves jerkily, ‘jumping’ from one year to the next 12 times in total. This is a bit clunky, which is why it’s good we have another option.
This option smoothes the transition between different ‘frames’, because it interpolates and adds transitional years where there are gaps in the timeseries data.
anim2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +
geom_point() +
scale_x_log10() + # convert x to log scale
transition_time(year)
anim2
The much smoother movement in Option 2 will be much more noticeable if you add a title to the chart, that will page through the years corresponding to each frame.
Q5 Can you add a title to one or both of the animations above that will change in sync with the animation? [hint: search labeling for transition_states() and transition_time() functions respectively]
length(unique(gapminder$year)) # we see how many unique years there are in the data set, so we can use it later on.
## [1] 12
#Here is the code from above copy pasted with some additions.
anim2 <- ggplot(gapminder, aes(gdpPercap, lifeExp, size = pop)) +#Here we make an object named anim2, where we use the illustration tool ggplot and use it on the gapminder dataset. The aestetics of the illustration is afterwards determined with gdppercap as the x-axis. lifeExp as the y-axis and population as size of the points.
geom_point() + #We choose the style of the illustration.
scale_x_log10() + # convert x to log scale
transition_time(year) + # We say that the illustration should change acording to the variable year, that we find in the dataset.
labs(title = "{closest_state}") + #Here we give illustration name(s). The name of title should be the name of the state closest to the current frame.
transition_states(year, transition_length = 12, state_length = 1, wrap = TRUE) #Lastly we perfect when the title should change. First we decide that it should be dependent on the variable years, the the transition length (how many transitions that should be). The state_length decides how long each caption should stay up in seconds. Lastly wrap is optional and makes the illustration start over when it is finished.
anim2
Q6 Can you made the axes’ labels and units more readable? Consider expanding the abreviated lables as well as the scientific notation in the legend and x axis to whole numbers.[hint:search disabling scientific notation]
#Here is the code from above copy pasted with some additions.
options(scipen=999) #By adding this line of code we disable the scientific way of writing lables.
anim3 <- ggplot(gapminder, aes(x = gdpPercap, y = lifeExp, size = pop))+
geom_point() +
scale_x_log10() +
transition_time(year) +
labs(title = "{closest_state}", x = "GDP Per Capita", y = "Life Expectancy", size = "Population") +
transition_states(year, transition_length = 12, state_length = 1, wrap = TRUE) +
theme(axis.text.x = element_text(size = 12), #here we change the size of the labels.
axis.text.y = element_text(size = 12),
text = element_text(size = 16),
plot.title = element_text(hjust = 0.5))
anim3
Q7 Come up with a question you want to answer using the gapminder data and write it down. Then, create a data visualisation that answers the question and explain how your visualization answers the question. (Example: you wish to see what was mean life expectancy across the continents in the year you were born versus your parents’ birth years). [hint: if you wish to have more data than is in the filtered gapminder, you can load either the gapminder_unfiltered dataset and download more at https://www.gapminder.org/data/ ]
My question: Which country in Africa had the biggest drop in life expectance and how did that countries dewellopment in life expectancy look in the years from 1952-2007
africa <- ggplot(subset(gapminder, continent == "Africa"), aes( x = year, y = lifeExp, size = pop)) +
geom_point() +
scale_x_log10() +
transition_time(year) +
transition_states(year, transition_length = 12, state_length = 1, wrap = TRUE)
africa
#Here i made a plot that looks at all the countries in Africa and their development in the years from 1952 to 2007 when we are looking at the population and its life expectancy. From the graph it is clear to see that one countries life expectancy drops dramatically. Therefore we take the next step to be sure which country that is.
buttom10 <- gapminder %>% #We choose to look at the gapminder dataset and add pipes to it, so we can send an output of one fucntion directly to another.
filter(year == 1992) %>%
filter(continent == "Africa") %>%
select(country , lifeExp) %>% #then we select or choose to look at the countries and their gdpPercap, as everything else is irelevant right now
arrange(desc(lifeExp)) %>% #lastly, we arange our data in a decending order so we have the richest nation first.
tail(10)
buttom10
## # A tibble: 10 x 2
## country lifeExp
## <fct> <dbl>
## 1 Zambia 46.1
## 2 Congo, Dem. Rep. 45.5
## 3 Burundi 44.7
## 4 Mozambique 44.3
## 5 Guinea-Bissau 43.3
## 6 Liberia 40.8
## 7 Angola 40.6
## 8 Somalia 39.7
## 9 Sierra Leone 38.3
## 10 Rwanda 23.6
#Here start by filtering the data to look at the year of the drop in life expectancy in 1992 in Africa to see which country that drops dramatically and as we see from the table it is Rwanda
rwanda <- ggplot(subset(gapminder, country == "Rwanda"), aes( x = year, y = lifeExp, size = pop, color = country)) +
geom_point() + #geom_point() gør at vi får scatter plots altså prikker i vores kordinatsystem
scale_x_log10() +
transition_time(year) +
transition_states(year, transition_length = 12, state_length = 1, wrap = TRUE)
rwanda
#As we see from the personal graph of Rwanda they have a masive drop in life expectance in 1992 but i rises quickly again. Interestingly enough the number in population does not seem to drop with the life expectance.